package com.m3839.sdk.common.http.listener;

import android.text.TextUtils;

import com.m3839.sdk.common.core.ApiError;
import com.m3839.sdk.common.core.ErrorConstant;
import com.m3839.sdk.common.util.HandlerUtils;

import org.json.JSONException;

/**
 * @author ChenBaoyang
 * @description: SimpleHttpRequestListener
 * @date 2021/11/13 10:37
 */
public abstract class SimpleHttpRequestListener implements OnHttpRequestListener{

    @Override
    public void onResponseSuccess(String response) throws Exception {
        HandlerUtils.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (TextUtils.isEmpty(response)) {
                        onResponseError(ErrorConstant.HYKB_CODE_SERVER_EXCEPTION,
                                ErrorConstant.ERR_MSG_SERVER_EXCEPTION);
                        return;
                    }

                    onResult(response);
                } catch (JSONException e) {
                    onResponseError(ErrorConstant.HYKB_CODE_SERVER_EXCEPTION, e.getMessage());
                }
            }
        });

    }

    @Override
    public void onResponseError(int code, String errorMessage) {
        HandlerUtils.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                ApiError apiError = new ApiError(code, errorMessage);
                onError(apiError);
            }
        });

    }

    /**
     * 请求接口成功的回调
     *
     * @param response
     * @throws JSONException
     */
    public abstract void onResult(String response) throws JSONException;

    public abstract void onError(ApiError apiError);

}
